<?php
namespace Modules\Frontend\Controllers;

class TradeSellController extends \Phalcon\Mvc\Controller {
  public function beforeExecuteRoute() {
    \Components\Utils::isClosedFrontent($this);
  }

  public function initialize() {
    $this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');
  }

  public function freeze() {
    $service = $this -> trade::getSellServiceInstance() -> find([
      'conditions' => 'status = 3 AND last_time < ' . (time() - 21600)
    ]);
    if($service['code'] != 0) {
      return false;
    }
    foreach($service['trade_sell'] as $trade_sell) {
      $serviceUser = $this -> account::getServiceInstance() -> findFirstById($trade_sell -> from_user_id);
      $serviceUser['user'] -> status = 2;
      if(!$serviceUser['user'] -> save())  { throw new \Exception('取消失败'); }

      $this -> status($trade_sell -> trade_sell_id, 6);
    }
  }

  public function indexAction() {
    $serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
    if($serviceUser['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
    }

    $query = $this -> request -> getQuery();
    if(!isset($query['page'])) {
      $query['page'] = 1;
    } else if($query['page'] <= 0)  {
      $query['page'] = 1;
    } else {
      $query['page'] = abs($query['page']);
    }

    if(!isset($query['limit'])) {
      $query['limit'] = 10;
    } else if($query['limit'] <= 0)  {
      $query['limit'] = 10;
    } else {
      $query['limit'] = abs($query['limit']);
    }

    $this -> freeze();

    $service = $this -> trade::getSellServiceInstance() -> pager([
      'conditions' => 'from_user_id = ' . $serviceUser['user'] -> user_id,
      'order' => 'status ASC,create_time DESC'
    ], $query['limit'], $query['page']);
    if($service['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
    }

    return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'pager' => $service['pager']]);
  }

  public function findFirstByIdAction($id) {
    $serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
    if($serviceUser['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]); }

    $serviceSell = $this -> trade::getSellServiceInstance() -> findFirstById($id);
    if($serviceSell['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceSell['code'],'msg'=>'销售订单获取失败']); }
    //if($serviceSell['trade_sell'] -> status != 3) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'销售订单已确认收款']); }

    $serviceBuy = $this -> trade::getBuyServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> trade_buy_id);
    if($serviceBuy['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceBuy['code'],'msg'=>'进货订单获取失败']); }
    //if($serviceBuy['trade_buy'] -> status != 3) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'进货订单已确认收款']); }

    $serviceUserBuy = $this -> account::getServiceInstance() -> findFirstById($serviceBuy['trade_buy'] -> from_user_id);
    if($serviceUserBuy['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUserBuy['code'],'msg'=>$serviceUserBuy['message']]); }
    if($serviceUserBuy['user'] -> pid <= 0) {
      $serviceParentUserBuy['user'] = ['cellphone' => '无推荐人'];
    } else {
      $serviceParentUserBuy = $this -> account::getServiceInstance() -> findFirstById($serviceUserBuy['user'] -> pid);
      if($serviceParentUserBuy['code'] != 0) {
        $serviceParentUserBuy['user'] = ['cellphone' => '无推荐人'];
      }
    }

    $serviceBankInfo = $this -> account::getBankInfoServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> user_bank_info_id);
    if($serviceBankInfo['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceBankInfo['code'],'msg'=>'银行卡信息获取失败']); }

    return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'user_buy' =>$serviceUserBuy['user'],'parent_user_buy'=>$serviceParentUserBuy['user'],'trade_buy' => $serviceBuy['trade_buy'],'trade_sell' => $serviceSell['trade_sell'], 'user_bank_info' => $serviceBankInfo['user_bank_info']]);
  }

  public function status($id, $status) {
    $serviceSell = $this -> trade::getSellServiceInstance() -> findFirstById($id);
    if($serviceSell['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceSell['code'],'msg'=>'销售订单获取失败']); }
    if($serviceSell['trade_sell'] -> status != 3) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'销售订单已确认收款']); }

    $serviceBuy = $this -> trade::getBuyServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> trade_buy_id);
    if($serviceBuy['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceBuy['code'],'msg'=>'进货订单获取失败']); }
    if($serviceBuy['trade_buy'] -> status != 3) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'进货订单已确认收款']); }

    $serviceUserBuy = $this -> account::getServiceInstance() -> findFirstById($serviceBuy['trade_buy'] -> from_user_id);
    if($serviceUserBuy['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUserBuy['code'],'msg'=>$serviceUserBuy['message']]); }

    $currentTime = time();
    $this -> db -> begin();
    try {
      switch($status) {
        case 6:
        case '6':
          // 判断是否第一次
          if($serviceBuy['trade_buy'] -> is_first == '0' && $serviceUserBuy['user'] -> pid > 0) {
            $tAmount = 0;
            $pServiceBuy = $this -> trade::getBuyServiceInstance() -> findFirst([
              'conditions' => 'status = 6 AND from_user_id = ' . $serviceUserBuy['user'] -> pid,
              'order' => 'trade_buy_id DESC'
            ]);
            if($pServiceBuy['code'] != 0) {
              $tAmount = 0;
            } else {
              if($pServiceBuy['trade_buy'] -> original_amount > $serviceBuy['trade_buy']->original_amount) {
                $tAmount = $serviceBuy['trade_buy'] -> original_amount;
              } else {
                $tAmount = $pServiceBuy['trade_buy'] -> original_amount;
              }
              $tAmount *= 0.05;
            }

            if($tAmount > 0) {
              $tAmount *= ($serviceBuy['trade_buy'] -> amount / $serviceBuy['trade_buy'] -> original_amount);
              $tradeBuyBusinessDataP = ['type'=>2,'amount'=>$tAmount*0.7,'user_id'=>$serviceUserBuy['user'] -> pid];
              $tradeBuyShopDataP = ['type'=>3,'amount'=>$tAmount*0.3,'user_id'=>$serviceUserBuy['user'] -> pid];

              $this -> account::getWalletServiceInstance() -> updateIncAmount($tradeBuyBusinessDataP);
              $this -> account::getWalletServiceInstance() -> updateIncAmount($tradeBuyShopDataP);
            }
          }

          // 判断0-3小时
          if($serviceBuy['trade_buy'] -> last_time + 10800 >= $currentTime) { $serviceBuy['trade_buy'] -> profit += 5; }
          if($serviceBuy['trade_buy'] -> loop_number == 6) { $serviceBuy['trade_buy'] -> profit = 0; }
          

          // 加零售积分
          $tradeBuyRetailData = ['type'=>1,'user_id'=>$serviceBuy['trade_buy'] -> from_user_id];
          $tradeBuyRetailData['amount'] = $serviceBuy['trade_buy'] -> amount * ($serviceBuy['trade_buy'] -> profit / 100);
          $tradeBuyRetailData['amount'] += $serviceBuy['trade_buy'] -> amount;
          $serviceRetail = $this -> account::getWalletServiceInstance() -> updateIncAmount($tradeBuyRetailData);
          if($serviceRetail['code'] != 0) { throw new \Exception($serviceRetail['message']); }

          // 加商城积分
          /*
          $tradeBuyShopData = ['type'=>3,'user_id'=>$serviceBuy['trade_buy'] -> from_user_id];
          if($serviceBuy['trade_buy'] -> amount < 10000) { $tradeBuyShopData['amount'] = $serviceBuy['trade_buy'] -> amount * 0.02;
          } else if($serviceBuy['trade_buy'] -> amount >= 10000) { $tradeBuyShopData['amount'] = $serviceBuy['trade_buy'] -> amount * 0.01; }
          $serviceShop = $this -> account::getWalletServiceInstance() -> updateIncAmount($tradeBuyShopData);
          if($serviceShop['code'] != 0) { throw new \Exception($serviceShop['message']); }
          */
          $serviceBuyShop = $this -> account::getWalletServiceInstance() -> updateIncAmount(['type'=>3,'user_id'=>$serviceBuy['trade_buy'] -> from_user_id,'amount'=>$serviceBuy['trade_buy'] -> amount * 0.05]);
          if($serviceBuyShop['code'] != 0) { throw new \Exception($serviceBuyShop['message']); }

          // 推荐人等级奖励
          if($serviceUserBuy['user'] -> pid != 0) {
            $currentParentUserBuy = $this -> account::getServiceInstance() -> findFirstById($serviceUserBuy['user'] -> pid);
            for($i=1;$i<=5;$i++) {
              $tAmount = 0;

              switch($i) {
                case 1:
                case '1':
                  if($currentParentUserBuy['user'] -> level >= '2') {
                    $pServiceBuy = $this -> trade::getBuyServiceInstance() -> findFirst([
                      'conditions' => 'status = 6 AND from_user_id = ' . $currentParentUserBuy['user']->user_id,
                      'order' => 'trade_buy_id DESC'
                    ]);
                    if($pServiceBuy['code'] != 0) {
                      $tAmount = 0;
                    } else {
                      if($pServiceBuy['trade_buy'] -> original_amount > $serviceBuy['trade_buy']->original_amount) {
                        $tAmount = $serviceBuy['trade_buy'] -> original_amount;
                      } else {
                        $tAmount = $pServiceBuy['trade_buy'] -> original_amount;
                      }
                      if($pServiceBuy['trade_buy'] -> original_amount >= 10000) {
                        $tAmount = 10000;
                      }

                      $tAmount *= 0.05;
                    }
                  }
                  break;
                case 3:
                case '3':
                  if($currentParentUserBuy['user'] -> level >= '3') {
                    $pServiceBuy = $this -> trade::getBuyServiceInstance() -> findFirst([
                      'conditions' => 'status = 6 AND from_user_id = ' . $currentParentUserBuy['user']->user_id,
                      'order' => 'trade_buy_id DESC'
                    ]);
                    if($pServiceBuy['code'] != 0) {
                      $tAmount = 0;
                    } else {
                      if($pServiceBuy['trade_buy'] -> original_amount > $serviceBuy['trade_buy']->original_amount) {
                        $tAmount = $serviceBuy['trade_buy'] -> original_amount;
                      } else {
                        $tAmount = $pServiceBuy['trade_buy'] -> original_amount;
                      }
                      if($pServiceBuy['trade_buy'] -> original_amount >= 20000) {
                        $tAmount = 20000;
                      }

                      $tAmount *= 0.03;
                    }
                  }
                  break;
                case 5:
                case '5':
                  if($currentParentUserBuy['user'] -> level >= '4') {
                    $pServiceBuy = $this -> trade::getBuyServiceInstance() -> findFirst([
                      'conditions' => 'status = 6 AND from_user_id = ' . $currentParentUserBuy['user']->user_id,
                      'order' => 'trade_buy_id DESC'
                    ]);
                    if($pServiceBuy['code'] != 0) {
                      $tAmount = 0;
                    } else {
                      if($pServiceBuy['trade_buy'] -> original_amount > $serviceBuy['trade_buy']->original_amount) {
                        $tAmount = $serviceBuy['trade_buy'] -> original_amount;
                      } else {
                        $tAmount = $pServiceBuy['trade_buy'] -> original_amount;
                      }

                      $tAmount *= 0.01;
                    }
                  }
                  break;
              }

              if($tAmount > 0) {
                $tAmount *= ($serviceBuy['trade_buy'] -> amount / $serviceBuy['trade_buy'] -> original_amount);
                $this -> account::getWalletServiceInstance() -> updateIncAmount(['type'=>2,'amount'=>$tAmount*0.7,'user_id'=>$currentParentUserBuy['user']->user_id]);
                $this -> account::getWalletServiceInstance() -> updateIncAmount(['type'=>3,'amount'=>$tAmount*0.3,'user_id'=>$currentParentUserBuy['user']->user_id]);
                //if($serviceShop['code'] != 0) { throw new \Exception($serviceShop['message']); }
              }

              if($currentParentUserBuy['code'] != 0) { break; }

              if($currentParentUserBuy['user'] -> pid <= 0) { break; }
    
              $currentParentUserBuy = $this -> account::getServiceInstance() -> findFirstById($currentParentUserBuy['user'] -> pid);
            }
          }

          break;
      }

      $serviceBuy['trade_buy'] -> status = $status;
      $serviceSell['trade_sell'] -> status = $status;

      $serviceBuy['trade_buy'] -> last_time = time();
      $serviceSell['trade_sell'] -> last_time = $serviceBuy['trade_buy'] -> last_time;

      if(!$serviceBuy['trade_buy'] -> save()) { throw new \Exception('确认失败'); }
      if(!$serviceSell['trade_sell'] -> save()) { throw new \Exception('确认失败'); }

      $this -> db -> commit();
    } catch(\Exception $e) {
      $this -> db -> rollback();

      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
    }

    return $this -> response -> setJsonContent(['code'=>0,'msg'=>'确认成功']);
  }
  
  public function statusAction($id, $status) {
    $serviceUserSell = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
    if($serviceUserSell['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUserSell['code'],'msg'=>$serviceUserSell['message']]); }

    $post = $this -> request -> getPost();
    if(!$this -> security -> checkHash($post['safePassword'], $serviceUserSell['user'] -> safe_password)) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'安全密码错误']); }

    return $this -> status($id, $status);
  }

  public function createAction() {
    $post = $this -> request -> getPost();

    if($post['amount'] <= 0) {
      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量不能少于0']);
    }

    if($post['amount'] < 2000) {
      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量不能少于2000']);
    }

    if(($post['amount'] % 100) != 0) {
      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量输入有误']);
    }

    if(!isset($post['user_bank_info_id']) || $post['user_bank_info_id'] <= 0) {
      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'请选择收款账号']);
    }

    $serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
    if($serviceUser['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
    }

    if(!$this -> security -> checkHash($post['safePassword'], $serviceUser['user'] -> safe_password)) {
      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'安全密码错误']);
    }

    $serviceUserWallet = $this -> account::getWalletServiceInstance() -> findFirstById($serviceUser['user'] -> user_id);
    if($serviceUserWallet['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$serviceUserWallet['code'],'msg'=>$serviceUserWallet['message']]);
    }

    $findTradeSell = $this -> trade::getSellServiceInstance() -> findFirst([
      'conditions' => 'from_user_id = ' . $serviceUser['user'] -> user_id,
      'order' => 'trade_sell_id DESC'
    ]);
    if($findTradeSell['code'] == 0 && $findTradeSell['trade_sell'] -> status != 6 && $findTradeSell['trade_sell'] -> status != 7) {
      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'请等候上一单匹配完成']);
    }

    $this -> db -> begin();
    try {
      $serviceRetail = $this -> account::getWalletServiceInstance() -> updateDecAmount(['type'=>1,'amount'=>$post['amount'],'user_id'=>$serviceUser['user'] -> user_id]);
      if($serviceRetail['code'] != 0) { throw new \Exception($serviceRetail['message']); }
      //if($serviceRetail['code'] != 0) { throw new \Exception('销售失败'); }

      $createTrade = $this -> trade::getSellServiceInstance() -> create([
        'trade_buy_id' => 0,
        'from_user_id' => $serviceUser['user'] -> user_id,
        'to_user_id' => 0,
        'user_bank_info_id' => $post['user_bank_info_id'],
        'amount' => $post['amount'],
        'original_amount' => $post['amount'],
        'create_time' => time(),
        'last_time' => time(),
        'status' => 0,
      ]);
      if($createTrade['code'] != 0) {
        throw new \Exception($createTrade['message']);
      }

      $this -> db -> commit();
    } catch(\Exception $e) {
      $this -> db -> rollback();

      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
    }

    return $this -> response -> setJsonContent(['code'=>0,'msg'=>'销售成功']);
  }

  public function cancalAction($id) {
    $serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
    if($serviceUser['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
    }

    $findFirstTradeSell = $this -> trade::getSellServiceInstance() -> findFirst([
      'conditions' => 'trade_sell_id = ' . $id . ' AND from_user_id = ' . $serviceUser['user'] -> user_id
    ]);
    if($findFirstTradeSell['code'] != 0) {
      return $this -> response -> setJsonContent(['code'=>$findFirstTradeSell['code'],'msg'=>$findFirstTradeSell['message']]);
    }
    if($findFirstTradeSell['trade_sell'] -> status != 0) {
      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'订单操作错误!']);
    }

    $this -> db -> begin();
    try {
      $serviceTrade = $this -> account::getWalletServiceInstance() -> updateIncAmount(['type'=>1,'amount'=>$findFirstTradeSell['trade_sell'] -> amount,'user_id'=>$findFirstTradeSell['trade_sell'] -> from_user_id]);
      if($serviceTrade['code'] != 0) { throw new \Exception('取消失败'); }

      $findFirstTradeSell['trade_sell'] -> trade_buy_id = 0;
      $findFirstTradeSell['trade_sell'] -> to_user_id = 0;
      $findFirstTradeSell['trade_sell'] -> status = 7;
      if(!$findFirstTradeSell['trade_sell'] -> save())  { throw new \Exception('取消失败'); }

      $this -> db -> commit();
    } catch(\Exception $e) {
      $this -> db -> rollback();

      return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
    }

    return $this -> response -> setJsonContent(['code'=>0,'msg'=>'取消成功']);
  }
}